<template>
  <p-tree-select
    allowClear
    labelInValue
    style="width: 100%"
    :disabled="disabled"
    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
    :placeholder="placeholder"
    :loadData="asyncLoadTreeData"
    :value="treeValue"
    :treeData="treeData"
    :multiple="multiple"
    @change="onChange"
    @search="onSearch">
  </p-tree-select>
</template>
<script>

  /*
  * 异步树加载组件 通过传入表名 显示字段 存储字段 加载一个树控件
  * <j-tree-select dict="aa_tree_test,aad,id" pid-field="pid" ></j-tree-select>
  * */
  import { getAction } from '@/api/manage'

  export default {
    name: 'JTreeSelect',
    props: {
      value:{
        type: String,
        required: false
      },
      placeholder:{
        type: String,
        default: '请选择',
        required: false
      },
      dict:{
        type: String,
        default: '',
        required: false
      },
      pidField:{
        type: String,
        default: '',
        required: false
      },
      pidValue:{
        type: String,
        default: '',
        required: false
      },
      disabled:{
        type:Boolean,
        default:false,
        required:false
      },
      hasChildField:{
        type: String,
        default: '',
        required: false
      },
      condition:{
        type:String,
        default:'',
        required:false
      },
      // 是否支持多选
      multiple: {
        type: Boolean,
        default: false,
      },
      loadTriggleChange:{
        type: Boolean,
        default: false,
        required:false
      },
      url: {
        type: String,
        default: '/basic-business/sys/dict/loadTreeData'
      },
      view: {
        type: String,
        default: '/basic-business/sys/dict/loadTreeData'
      }
    },
    data () {
      return {
        treeValue: null,
        treeData:[{title: '工厂', value: '1', key: '1',children:[]}],
        tableName:"",
        text:"",
        code:"",

      }
    },
    watch: {
      value (val) {
        
      },
      dict(){
        // this.initDictInfo() 
      }
    },
    created(){
      this.validateProp().then(()=>{
        this.initDictInfo() 
      })
    },
    methods: {   
      initDictInfo(){
        // 显示树状结构的值
        this.treeValue = {
          label: this.pidField || '',
          value: this.value || ''
        }
      },
        
      findItemFromTree(tree, key) {
        var stark = [];
        stark = stark.concat(tree);
        while(stark.length) {
          var temp = stark.shift();
          if(temp.children) {
            stark = stark.concat(temp.children);
          }
          if(temp.key == key) {
            return temp;
          }
        }
      },
      asyncLoadTreeData (treeNode) {
        return new Promise((resolve) => {
          if (treeNode.$vnode.children) {
            resolve()
            return
          }
          let pid = treeNode.$vnode.key
          let param = {
            pid:pid,
            tableName:this.tableName,
            text:this.text,
            code:this.code,
            pidField:this.pidField,
            hasChildField:this.hasChildField,
            condition:this.condition
          }
          getAction(this.url,param).then(res=>{
            if(res.success){
              let records = res.data || []
              let result = records.map(v => {
                v.key = v.id.toString()
                v.title = v.phname
                v.parentId = v.pid.toString()
                v.value = v.id.toString()
                v.label = v.phname
                v.isLeaf = v.hasChild == '1' ? false : true
                return v
              }) 
              this.addChildren(pid, result,this.treeData)
              this.treeData = [...this.treeData]
            }
            resolve()
          })
        })
      },
      addChildren(pid,children,treeArray){
        if(treeArray && treeArray.length>0){
          for(let item of treeArray){
            if(item.key == pid){
              if(!children || children.length==0){
                item.isLeaf=true
              }else{
                item.children = children
              }
              break
            }else{
              this.addChildren(pid,children,item.children)
            }
          }
        }
      },
      loadRoot(){ 
        getAction(this.view).then(res=>{
          if(res.success && res.data){ 
            let records = res.data.records || []
            let result = records.map(v => {
              v.key = v.id.toString()
              v.title = v.phname
              v.value = v.id.toString()
              v.label = v.phname
              v.parentId = v.pid.toString()
              v.isLeaf = v.hasChild == '1' ? false : true
              return v
            }) 
            this.treeData[0].children = [...result]
          }else{
            console.log("数根节点查询结果-else",res)
          }
        })
      },
      onChange(value,label,extra){
        if(!value){
          this.$emit('change', '');
          this.treeValue = null
        } else if (value instanceof Array) {
          this.$emit('change', value.map(item => item.value).join(','))
          this.treeValue = value
        } else {
          this.$emit('change', value.value,value.label)
          this.treeValue = value
        }

      },
      onSearch(value){
        console.log(value)
      },
      getCurrTreeData(){
        return this.treeData
      },
      validateProp(){
        let mycondition = this.condition
        return new Promise((resolve,reject)=>{
          if(!mycondition){
            resolve();
          }else{
            try {
              let test=JSON.parse(mycondition);
              if(typeof test == 'object' && test){
                resolve()
              }else{
                this.$message.error("组件JTreeSelect-condition传值有误，需要一个json字符串!")
                reject()
              }
            } catch(e) {
              this.$message.error("组件JTreeSelect-condition传值有误，需要一个json字符串!")
              reject()
            }
          }
        })
      }
    },
    //2.2新增 在组件内定义 指定父组件调用时候的传值属性和事件类型 这个牛逼
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>
